//
//  LCFxzcTableViewController.m
//  JKFuYinProject
//
//  Created by jiukuyinyue on 2017/9/7.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LCFxzcTableViewController.h"
#import "LCCycleModel.h"
#import "LCFxzcTitleTableViewCell.h"
#import "LCFxzcListTitleTableViewCell.h"

#import "LSZMoveCheckVC.h"//查看更多   不是这个地方的

#define FxzcTitleCell @"FxzcTitleCell"
#define FxzcListTitleCell @"FxzcListTitleCell"
#define FxzcListCell @"FxzcListCell"


@interface LCFxzcTableViewController () <SDCycleScrollViewDelegate,LCHorizontalGrideViewDataSource,LCHorizontalGrideViewDelegate>

///图片轮播器
@property (strong, nonatomic) SDCycleScrollView *cycleScrollView;
///中间按钮
@property (strong,nonatomic) LCHorizontalGrideView  *horizontalGrideView;


@end

@implementation LCFxzcTableViewController{
    NSArray<LCCycleModel *> *_cycleArray;//轮播器
    NSArray *_thirdLoginArray;
}
-(void)viewWillAppear:(BOOL)animated
{
    [self loadData];
}
- (void)loadRequest
{
     __weak typeof(self) weakSelf = self;
    [LSZRequestResolutionDic initWithDedication:^(BOOL isOK, NSString * Str, LSZDedicationManager * dicManager) {
        if(isOK == YES){
            weakSelf.dictionMg = dicManager;
            [weakSelf.tableView reloadData];
        }else{
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",Str]];
            [SVProgressHUD dismissWithDelay:1];
        }
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBColor(236, 236, 236);
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    MJRefreshGifHeader *refreshGifHeader = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    // 隐藏时间
    refreshGifHeader.lastUpdatedTimeLabel.hidden = YES;
    // 设置header
    self.tableView.mj_header = refreshGifHeader;
    
    [self setupHeaderView];
    [self setupUI];
//    [self loadData];
}
- (void)setupUI {
    //添加以下代码关闭估算行高
     self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 20, 0, 20)];
    [self.tableView registerNib:[UINib nibWithNibName:@"LCFxzcTitleTableViewCell" bundle:nil] forCellReuseIdentifier:FxzcTitleCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LCFxzcListTitleTableViewCell" bundle:nil] forCellReuseIdentifier:FxzcListTitleCell];
    [self.tableView registerClass:[LCFxzcListTitleTableViewCell class] forCellReuseIdentifier:@"LCFxzcListTitleTableViewCell"];
    
    [self.tableView registerClass:[LSZDedicationTableViewCell class] forCellReuseIdentifier:@"LSZDedicationTableViewCell"];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.tabBarController.tabBar.translucent = NO;
}
#pragma mark - 搜索不要了
- (void)setSearchControllerView{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,ScreenWidth,40)];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,7,ScreenWidth / 3, 30)];
    imageView.image = [UIImage imageNamed:@"jkfylogo"];
    [view addSubview:imageView];
    //背景颜色
    LCLoginTextField *textField = [[LCLoginTextField alloc] initWithFrame:CGRectMake(ScreenWidth / 3 + 6,7,ScreenWidth *2 / 3 - 22,30)];
//    _searchBar = textField;
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.adjustsFontSizeToFitWidth = YES;
    textField.placeholder = @"搜索圣经、赞美诗...";
    [view addSubview:textField];
    self.navigationItem.titleView = view;
}
#pragma mark- 请求数据和轮播图
-(void)loadData{
    [self loadCycleScrollViewData];
    [self loadRequest];
}
#pragma mark - 轮播图
-(void)loadCycleScrollViewData{
        [kNetworkTool POSTFuYinWithUrlString:DONATE_CAROUSEL input:@{} success:^(NSDictionary *dict) {
            
            _cycleArray = [NSArray yy_modelArrayWithClass:[LCCycleModel class] json:dict[@"data"]];
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                //
                NSMutableArray *imagesURLStrings = [NSMutableArray arrayWithCapacity:_cycleArray.count];
                for (LCCycleModel *model in _cycleArray) {
                    if (model != nil) {
                        [imagesURLStrings addObject:model.pic];
                    }
                }
                if (imagesURLStrings.count == 0) {
                    _cycleScrollView.imageURLStringsGroup = @[@"devotion_bannerA",@"devotion_bannerB"];
                }else{
                    _cycleScrollView.imageURLStringsGroup = imagesURLStrings;
                }

            }];
        } failure:^(NSError *error) {
            NSLog(@"error = %@", error);
        }];
}
// 返回共享一个图片轮播器
- (SDCycleScrollView *)cycleScrollView {
    if(_cycleScrollView == nil) {
        _cycleScrollView = [SDCycleScrollView new];
        _cycleScrollView.placeholderImage = [UIImage imageNamed:@"placeholder"];
        _cycleScrollView.delegate = self;
        //        _cycleScrollView.currentPageDotColor = [UIColor whiteColor];
        _cycleScrollView.autoScrollTimeInterval = 5;// 自动滚动时间间隔
        [_cycleScrollView.layer setMasksToBounds:YES];
        [_cycleScrollView.layer setCornerRadius:4];
    }
    return _cycleScrollView;
}
#pragma mark -  SDCycleScrollView Delegate  -
#pragma mark - 轮播图的点击事件
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
//    __weak typeof(self) weakSelf = self;
    LCCycleModel *cycleDict = _cycleArray[index];
    NSString * url = [NSString stringWithFormat:@"%@",cycleDict.url];
  
   if([url rangeOfString:@"?usercode="].location !=NSNotFound)
    {
        if ([[_UserM usercode] isEqualToString:@""]) {
            UIStoryboard *sb = [UIStoryboard storyboardWithName:@"AccLogin" bundle:nil];
            UIViewController *controller = [sb instantiateInitialViewController];
            [self.navigationController pushViewController:controller animated:YES];
            return;
        }else{
            url = [NSString stringWithFormat:@"%@%@",url,[_UserM usercode]];
        }
    }
     //这个地方也要跳转
     WYWebController *viewController = [[WYWebController alloc] init];
    
    viewController.url = url;
    [self.navigationController pushViewController:viewController animated:YES];
}
-(LCHorizontalGrideView *)horizontalGrideView{
    if (_horizontalGrideView == nil) {
        _horizontalGrideView = [[LCHorizontalGrideView alloc] init];
        _horizontalGrideView.delegate = self;
        _horizontalGrideView.dataSource = self;
        
        _thirdLoginArray = [[NSArray alloc] initWithObjects:@"我要奉献",@"报名事工",@"公示平台", nil];
        [_horizontalGrideView reloadData];
    }
    return _horizontalGrideView;
}

-(void)setupHeaderView{
    UIView *headView = [[UIView alloc] init];
    headView.backgroundColor = [UIColor whiteColor];

    CGFloat height = 160;//轮播图高度
    UIView * oneView = [[UIView alloc]init];
    oneView.frame = CGRectMake(0, 0, ScreenWidth, height/2+10);
    oneView.backgroundColor = RGBColor(228, 83, 77);
    [headView addSubview:oneView];

    UIView * TwoView = [[UIView alloc]init];
    TwoView.frame = CGRectMake(0, CGRectGetMaxY(oneView.frame), ScreenWidth, height/2);
    TwoView.backgroundColor = [UIColor whiteColor];
    [headView addSubview:TwoView];

    self.cycleScrollView.frame = CGRectMake(10, 10, self.view.bounds.size.width-20, height);
    [headView addSubview:self.cycleScrollView];
    self.horizontalGrideView.celltype = 1;
    
    CGFloat horizontalHeight = 0;
    
    if (ScreenWidth == 320) {
        horizontalHeight = 6;
    }else if ((ScreenWidth == 375)){
        horizontalHeight = 14;
    }
    else{
        horizontalHeight = 19;
    }
    
    self.horizontalGrideView.frame = CGRectMake(0, CGRectGetMaxY(self.cycleScrollView.frame), self.view.bounds.size.width, 100 + horizontalHeight);
    self.horizontalGrideView.backgroundColor = [UIColor whiteColor];
    [headView addSubview:self.horizontalGrideView];
    
    headView.frame = CGRectMake(0, 0, self.view.bounds.size.width, CGRectGetMaxY(self.horizontalGrideView.frame));
    self.tableView.tableHeaderView = headView;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dictionMg.mutDataArray.count+2;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30;
}
#pragma mark -  cell  -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        LCFxzcTitleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:FxzcTitleCell forIndexPath:indexPath];
        cell.textLabel.text = @"实时奉献";

        UIButton *button = [[UIButton alloc] init];
        [button setTitle:@"我的明细" forState:UIControlStateNormal];
        [button setTitleColor:RGBColor(124, 185, 249) forState:UIControlStateNormal];
        [button addTarget:self action:@selector(clickListDetails:) forControlEvents:UIControlEventTouchUpInside];
        [button sizeToFit];
        cell.accessoryView = button;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;

    }
   else if (indexPath.row == 1) {
       LCFxzcListTitleTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LCFxzcListTitleTableViewCell" forIndexPath:indexPath];
       if (!cell) {
           cell = [[LCFxzcListTitleTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"LCFxzcListTitleTableViewCell"];
       }
       cell.selectionStyle = UITableViewCellSelectionStyleNone;
       return cell;
    }
   else{
       //实时奉献调数据
       LSZDedicationTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZDedicationTableViewCell" forIndexPath:indexPath];
       if (!cell) {
           cell = [[LSZDedicationTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"LSZDedicationTableViewCell"];
       }
       LSZDedicationMg * lszDictionMg = nil;
       lszDictionMg =  self.dictionMg.mutDataArray[indexPath.row-2];
       NSString * nameStr = [NSString stringWithFormat:@"%@",lszDictionMg.username];
       NSString * genderStr = [[NSString alloc]initWithFormat:@"%@",lszDictionMg.gender];
 
       if ([nameStr isEqualToString:@""]||nameStr.length == 0) {
           cell.labelName.text = [NSString stringWithFormat:@"%@的fy_%@%@",lszDictionMg.location,lszDictionMg.uid,genderStr];
       }else{
           cell.labelName.text = [NSString stringWithFormat:@"%@%@%@",lszDictionMg.location,lszDictionMg.username,genderStr];
       }
       float money  = [lszDictionMg.cash floatValue] +[lszDictionMg.credit floatValue];
       cell.labelMoney.text = [NSString stringWithFormat:@"%.2f",money];
       cell.labelTime.text = [NSString stringWithFormat:@"%@",lszDictionMg.uptime];
       cell.selectionStyle = UITableViewCellSelectionStyleNone;
       return cell;
   }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row >1) {
        LSZDedicationMg * lszDictionMg = nil;
        lszDictionMg =  self.dictionMg.mutDataArray[indexPath.row-2];
        
        NSString * strLabelName  = [[NSString alloc]init];
        NSString * strName = [[NSString alloc]init];
        NSString * nameStrAndRegion = [NSString stringWithFormat:@"%@",lszDictionMg.username];
        NSString * genderStr = [NSString stringWithFormat:@"%@",lszDictionMg.gender];
        
        if ([nameStrAndRegion isEqualToString:@""]||nameStrAndRegion.length == 0) {
            strLabelName = [NSString stringWithFormat:@"%@的fy_%@%@",lszDictionMg.location,lszDictionMg.uid,genderStr];
            strName = [NSString stringWithFormat:@"fy_%@",lszDictionMg.uid];
        }else{
           strLabelName = [NSString stringWithFormat:@"%@%@%@",lszDictionMg.location,lszDictionMg.username,genderStr];
            strName = [NSString stringWithFormat:@"%@",lszDictionMg.username];
        }
        
        float money  = [lszDictionMg.cash floatValue] +[lszDictionMg.credit floatValue];

        LSZDonationDetailsVC * vc = [[LSZDonationDetailsVC alloc]init];
        vc.titleStr = [NSString stringWithFormat:@"九酷福音感谢%@  捐献%.2f 元,愿上帝保佑您,阿门!",strLabelName,money];
        vc.strName = strName;
        vc.messageStr = [NSString stringWithFormat:@"%@",lszDictionMg.note];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark -  详情跳转  -
-(void)clickListDetails:(UIButton *)sender {
    if ([[_UserM usercode] isEqualToString:@""]) {
        [self gotoLogIn];
    }else{
        LCBeautifulEssayController *controller = [[LCBeautifulEssayController alloc] init];
        controller.link = [NSString stringWithFormat:@"http://fuyin.app.inping.com/user/dedication?usercode=%@",[_UserM usercode]];
        [self.navigationController pushViewController:controller animated:YES];
    }
}
#pragma mark- 跳转登陆界面
-(void)gotoLogIn
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"AccLogin" bundle:nil];
    UIViewController *controller = [sb instantiateInitialViewController];
    [self.navigationController pushViewController:controller animated:YES];
}
#pragma mark - LCHorizontalGrideViewDataSource -
/**
 提供数据的数量
 @param horizontalGrideView 控件本身
 @return 返回数量
 */
- (NSInteger)numberOfItemsInHorizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView {
    return 3;
}
/**
 提供选项标题
 @param horizontalGrideView 当前控件
 @param index 选项下标
 @return 返回标题
 */
- (NSString *)horizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView titleForItemAtIndex:(NSInteger)index {
    return [NSString stringWithFormat:@"%@",_thirdLoginArray[index]];
}
/**
 提供选项的图标地址路径
 @param horizontalGrideView 当前控件
 @param index 选项下标
 @return 返回图标路径
 */
- (NSString *)horizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView iconURLForItemAtIndex:(NSInteger)index {
    if (index == 0) {
         return [NSString stringWithFormat:@"%@",@"devotion_icon_fengxian"];
    }else if (index == 1) {
        return [NSString stringWithFormat:@"%@",@"devotion_icon_baoming"];
    }else {
          return [NSString stringWithFormat:@"%@",@"devotion_icon_gongshi"];
    }
}
#pragma mark - LCHorizontalGrideViewDelegate -
- (NSInteger)numberOfRowsPerPageInHorizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView {
    return 1;//四舍五入
}
- (NSInteger)numberOfColumnsPerPageInHorizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView {
    return 3;
}
/**
 当选项被点击回调
 @param horizontalGrideView 当前控件
 @param index 点击下标
 */
#pragma mark - 奉献支持的我要奉献 报名事工 公示平台
- (void)horizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView didSelectItemAtIndex:(NSInteger)index {
    if (index == 2) {
        LCBeautifulEssayController *controller = [[LCBeautifulEssayController alloc] init];
        controller.link = [NSString stringWithFormat:@"http://fuyin.app.inping.com/user/notice?usercode=%@",[_UserM usercode]];
        [self.navigationController pushViewController:controller animated:YES];
    }else{
        if ([[_UserM usercode] isEqualToString:@""]) {
            [self goToLogin];
        }else{
            if (index == 0) {
                Class clz = NSClassFromString(@"LCRmbHtmlVC");
                UIViewController *viewController = [[clz alloc] init];
                [self.navigationController pushViewController:viewController animated:YES];
             }
            LCBeautifulEssayController *controller = [[LCBeautifulEssayController alloc] init];
            if (index == 1) {
                controller.link = [NSString stringWithFormat:@"http://fuyin.app.inping.com/user/recruit?usercode=%@",[_UserM usercode]];
                [self.navigationController pushViewController:controller animated:YES];
            }
            
        }
    }
}
-(void)goToLogin
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"AccLogin" bundle:nil];
    UIViewController *controller = [sb instantiateInitialViewController];
    [self.navigationController pushViewController:controller animated:YES];
}
/**
 返回当前选中的pageControl 颜色
 
 @param horizontalGrideView 当前控件
 @return 颜色
 */
- (UIColor *)colorForCurrentPageControlInHorizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView {
    return [UIColor whiteColor];
}

@end
